package com.test.lotterysystem.Service.Mq;

import com.test.lotterysystem.Comment.Constants.Constants;
import com.test.lotterysystem.Comment.Exception.ServiceException;
import com.test.lotterysystem.Comment.Utils.JacksonUtil;
import com.test.lotterysystem.Controller.Param.DrawPrizeParam;
import com.test.lotterysystem.Service.ActivityStatusChange.ActivityStatusChange;
import com.test.lotterysystem.Service.DTO.ConvertActivityStatusDTO;
import com.test.lotterysystem.Service.DrawPrizeService;
import com.test.lotterysystem.Service.Enum.ActivityEnum;
import com.test.lotterysystem.Service.Enum.ActivityPrizeEnum;
import com.test.lotterysystem.Service.Enum.ActivityUserEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

@Component
@RabbitListener(queues = Constants.QUEUE_NAME)
@Slf4j
public class RabbitMqReceiver {

    @Autowired
    private DrawPrizeService drawPrizeService;
    @Autowired
    private ActivityStatusChange activityStatusChange;

    @RabbitHandler
    public void process(Map<String, String> map) {
        log.info("接收方接收到数据...{}", map);
        DrawPrizeParam message = JacksonUtil.readValue(map.get("message"), DrawPrizeParam.class);

        try {
            // 校验接收到的消息
            if(!drawPrizeService.checkDrawPrizeMessage(message)){
                return;
            }

            // 转换状态 —— 有依赖关系，先后顺序（责任链模式），并且多个状态的转换操作流程类似（策略模式）
            ConvertActivityStatusDTO statusDTO = new ConvertActivityStatusDTO();
            statusDTO.setActivityId(message.getActivityId());
            statusDTO.setTargetActivityStatus(ActivityEnum.FINISH);
            statusDTO.setPrizeId(message.getPrizeId());
            statusDTO.setTargetPrizeStatus(ActivityPrizeEnum.COMPLETED);
            statusDTO.setUserIds(message.getWinnerList().stream().map(user->user.getUserId()).collect(Collectors.toList()));
            statusDTO.setTargetUserStatus(ActivityUserEnum.COMPLETED);

            activityStatusChange.changeStatus(statusDTO);

            // 保存数据

            // 发送消息提醒获奖者


        } catch (ServiceException serviceException) {
            log.error("转换数据发生异常!",serviceException);
            rollback(message);
            throw serviceException;
        } catch (Exception exception){
            log.error("处理 RabbitMQ 时发生异常!",exception);
            rollback(message);
            throw exception;
        }
    }
}
